package com.tjakus.arduino.bean;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import com.tjakus.arduino.hibernate.HibernateUtil;
import com.tjakus.arduino.hibernate.Sensors;
import com.tjakus.arduino.logging.Logging;
import com.tjakus.arduino.serial.ArduinoCommunicator;

public class CommandsBean {

	private List<Sensors> sensorsList = HibernateUtil.getSensorByChangeable(true);
	private String commandToSend = "SRV#LED#LED01#0";

	public List<Sensors> getSensorsList() {
		Logging.getLogger().info("CommandsBean - getSensorsList [ ]");
		return sensorsList;
	}

	public void setSensorsList(List<Sensors> newSensorsList) {
		this.sensorsList = newSensorsList;
	}

	public String getCommandToSend() {
		return commandToSend;
	}

	public void setCommandToSend(String newCommandToSend) {
		this.commandToSend = newCommandToSend;
	}

	public void submit() {
		Logging.getLogger().info("SensorsBean - submit [ ]");
		FacesContext context = FacesContext.getCurrentInstance();
		// Create current time stamp
		Date date = new Date();
		Timestamp newTimestamp = new Timestamp(date.getTime());
		for (Iterator<Sensors> iter = sensorsList.iterator(); iter.hasNext();) {
			Sensors sensorFromWeb = iter.next();
			Sensors sensorFromDB = HibernateUtil.getSensorBySensorId(sensorFromWeb
					.getSensorId());
			// if value has been changed
			if (!sensorFromWeb.getValue().equals(sensorFromDB.getValue())) {
				// set new time stamp
				sensorFromWeb.setTimestamp(newTimestamp);
				Logging.getLogger().info(
						"CommandsBean - submit [ " + sensorFromWeb.getValue() + " ]");
				ArduinoCommunicator.sendToArduino("SRV#" + sensorFromWeb.getType()
						+ "#" + sensorFromWeb.getSensorId() + "#"
						+ sensorFromWeb.getValue());
				boolean status = HibernateUtil.updateSensor(sensorFromWeb);
				if (status) {
					context
							.addMessage(null, new FacesMessage("Command sent to Arduino."));
				} else {
					context
							.addMessage(null, new FacesMessage("ERROR, command NOT send."));
				}
			}
		}
	}

	public void send() {
		Logging.getLogger().info(
				"CommandsBean - send [ " + this.getCommandToSend() + " ]");
		ArduinoCommunicator.sendToArduino(this.getCommandToSend());
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, new FacesMessage("Command sent to Arduino."));
	}

}
